<?php
/**
 * Documentation, License etc.
 *
 * @package girafplace
 */

include 'include.php';
include '_functions.php';

if(!$loggedin)
  die("You must be logged in to access this page");

if(!isset($_POST['name']))
  die("You should only access this file through the add file dialog.");
  
$name = addslashes($_POST['name']);
$description = addslashes($_POST['description']);
$abilities = array();

if (isset($_POST['abilities'])) {
	if (is_array($_POST['abilities'])) {
		foreach ($_POST['abilities'] as $abilityId) {
			$abilities[$abilityId] = '1';
		}
	} else {
		throw new Exception('HACKER!!!');
	}
}

$id = 0;

try {
	Connect();
	$id = addApplicationPre($name, $description, $_SESSION['adminId']);
	setAbilities($id, $abilities);

	uploadAPK($id);

	$file = ''. $id . '.apk';

	$apkInfo = getInfoFromApk($file, $id);

	$packageName = $apkInfo['package'];
	$version = $apkInfo['version'];
	$versionString = $apkInfo['versionString'];

	addApplicationPost($id, $packageName, $version, $versionString);

	removeOldPackage($packageName);

	//cronjobClearing();

	Close();

	header( 'Location: index.php' ) ;
} catch (Exception $e) {
	Connect();
	
	mysql_query("UPDATE applications SET state = 'ERROR' WHERE applicationId = $id");
	insertError($id, $e->getMessage());
	echo 'Error: ' . $e->getMessage();
}